<?php

namespace App\Console\Commands\Data;

use App\Imports\Area\AreaGradeImport;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
use Kuafu\File\PrivateFileUtil;
use Maatwebsite\Excel\Facades\Excel;

class AreaAppendGradeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'area:appendGrade';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '省市区增加城市分级+菜单等级字段';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     * @throws GuzzleException
     */
    public function handle(): int
    {
        $url                      = $this->ask('请输入excel地址 : ',
            'https://file.51kuafu.com/b1/c0/abfe89cb68800effb11b71a2508300a080d6dd103b5405da9cacfb4707a9.xlsx');
        AreaGradeImport::$command = $this;
        $pathInfo                 = parse_url($url);
        $client                   = new Client();
        $tempData                 = $client->request("get", $url)->getBody()->getContents();
        $file                     = md5($url) . date('YmdHis', time()) . "." . implode(".", $pathInfo)[1];
        Storage::disk("public")->put($file, $tempData);
        Excel::import(new AreaGradeImport(), storage_path("app/public") . "/{$file}");
        Storage::disk("public")->delete($file);
        return 0;
    }
}
